﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using A5Lib;
using System.Web.Security;

namespace A5Site
{
    public partial class Admin : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["myuser"] == null)
            {
                Response.Redirect("Home.aspx");
            }
            A5Lib.User usr = (A5Lib.User)Session["myuser"];            
            UserServices.UserServicesClient usc = new UserServices.UserServicesClient();
            if (!FormsAuthentication.Authenticate(usr.Username, usr.Password))
            {
                Response.Redirect("Login.aspx");
            }

        }

        protected override void OnLoadComplete(EventArgs e)
        {
            base.OnLoadComplete(e);

            ListBox1.Items.Clear();
            UserServices.UserServicesClient myProxy = new UserServices.UserServicesClient();

            string[] usersList;
            usersList = myProxy.GetAllUsernames();

            if (usersList != null)
            {

                foreach (string str in usersList)
                {
                    ListBox1.Items.Add(str);
                }
            }
        }

        protected void AddBtn_Click(object sender, EventArgs e)
        {
         
        }

        protected void AddBtn_Click1(object sender, EventArgs e)
        {
            UserServices.UserServicesClient myProxy1 = new UserServices.UserServicesClient();

            A5Lib.User user = new A5Lib.User();
            user.Username = TBNewUserName.Text;
            user.Password = TBNewUserPwd.Text;
            if (myProxy1.CheckUsernameExists(user.Username))
            {
                lbl_addUserError.Text = "Username exists.";
                return;
            }
            if (myProxy1.InputValidator(user.Username, 4, 20, false) &&
                myProxy1.InputValidator(user.Password, 4, 20, false))
                myProxy1.WriteUser(user, true);
            else
            {
                lbl_addUserError.Text = "Username and password must be alphanumeric, 4-20 characters.";
                return;
            }
            lbl_addUserError.Text = "User " + user.Username + " added successfully.";
        }

        protected void DeleteBtn_Click(object sender, EventArgs e)
        {
            UserServices.UserServicesClient myProxy2 = new UserServices.UserServicesClient();
            if (ListBox1.SelectedIndex >= 0)
            {
                myProxy2.DeleteUser(ListBox1.SelectedValue);
                DeleteSuccessLbl.Text = "User deleted successfully";
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            Response.Redirect("Home.aspx");
        }
    }
}